package lib.XML;

import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import settings.model.MappingBierdopjeScene;
import util.Downloader;

public class XMLTranslateBierScene {

    public static void Write(List<MappingBierdopjeScene> list, File f) throws Throwable {
        Document newDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Element rootElement = newDoc.createElement("Translations-Bierdopje-Scene");
        newDoc.appendChild(rootElement);

        for (MappingBierdopjeScene item : list) {
            Element translation = newDoc.createElement("translation");
            Element bier = newDoc.createElement("bierdopje");
            bier.appendChild(newDoc.createTextNode(item.getBierdopjeName()));
            translation.appendChild(bier);
            Element bierId = newDoc.createElement("bierdopjeid");
            bierId.appendChild(newDoc.createTextNode(Integer.toString(item.getBierdopjeId())));
            translation.appendChild(bierId);
            Element scene = newDoc.createElement("scene");
            scene.appendChild(newDoc.createTextNode(item.getSceneName()));
            translation.appendChild(scene);
            rootElement.appendChild(translation);
        }

        XMLHelper.writeToFile(f, newDoc);
    }

    public static ArrayList<MappingBierdopjeScene> Read(File f) throws Throwable {
        Document newDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f);
        return Read(newDoc);
    }
    
    public static ArrayList<MappingBierdopjeScene> getOnlineMappingCollection() throws Throwable{
    	URLConnection conn = new URL("http://jbiersubdownloader.googlecode.com/files/Mappings.xml").openConnection();
        conn.setReadTimeout(2000);
        return Read(XMLHelper.getDocument(Downloader.getUrlContents(conn)));
    }
    
    public static ArrayList<MappingBierdopjeScene> Read(Document newDoc) throws Throwable {
    	ArrayList<MappingBierdopjeScene> list = new ArrayList<MappingBierdopjeScene>();
        NodeList nList = newDoc.getElementsByTagName("translation");

        for (int i = 0; i < nList.getLength(); i++) {
            if (nList.item(i).getNodeType() == Node.ELEMENT_NODE) {
                String bier = XMLHelper.getStringTagValue("bierdopje", (Element) nList.item(i));
                int bierid = XMLHelper.getIntTagValue("bierdopjeid", (Element) nList.item(i));
                String scene = XMLHelper.getStringTagValue("scene", (Element) nList.item(i));
                MappingBierdopjeScene item = new MappingBierdopjeScene(bier, scene, bierid);
                list.add(item);
            }
        }
        return list;
    }
}
